import java.util.Stack;

public class StackTest {
    //逆波兰表达式
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < tokens.length; i++) {
            String s = tokens[i];
            //如果是运算符
            if(s.equals("+" ) || s.equals("-")  || s.equals("*") || s.equals( "/")) {
                //取出操作数，第一个操作数是右操作数，左边为第二个操作数
                switch(s) {
                    case "+":
                        int a = stack.pop();
                        int b = stack.pop();
                        stack.push(b+a);
                        break;
                    case "-":
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(b-a);
                        break;
                    case "*":
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(b*a);
                        break;
                    case "/":
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(b/a);
                        break;
                }
            }else{
                //否则是数字,放入栈中
                int num = Integer.parseInt(tokens[i]);
                stack.push(num);
            }
        }
        return stack.pop();
    }
}
